package com.ada.handler;

import com.ada.request.RpcRequest;
import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Component
public class UserServerHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        //如何符合规定，则调用本地方法，返回数据
        String pojoJson = msg.toString();
        RpcRequest rpcRequest = JSON.parseObject(pojoJson, RpcRequest.class);
        Object bean = context.getBean(rpcRequest.getClassName());
        try {
            Method method = bean.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParams().getClass());
            method.setAccessible(true);
            Object result = method.invoke(bean, rpcRequest.getParams());
            ctx.writeAndFlush(result.toString());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
}
